<template>
    <el-button type="primary" @click="addOrEditShow(0)">新增</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-button type="success" @click="batchOutBound">批量出库</el-button>
    <el-button type="success" @click="isOutBoundShow = true, outBoundSN = ''">连续出库</el-button>

    <el-form :inline="true" :model="requestData" class="demo-form-inline" style="margin-top: 20px;">
        <el-form-item label="序列号" style="width: 300px;">
            <el-input v-model="requestData.sn" placeholder="请输入序列号" clearable />
        </el-form-item>
        <el-form-item label="出库状态" style="width: 165px;">
            <el-select clearable v-model="requestData.outBound" placeholder="请选择" size="large" style="width: 100px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="设备名称" style="width: 240px;">
            <el-input v-model="requestData.name" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="型号" style="width: 240px;">
            <el-input v-model="requestData.model" placeholder="请输入型号" clearable />
        </el-form-item>
        <el-form-item label="设备状态" style="width: 240px;">
            <el-input v-model="requestData.status" placeholder="请输入设备状态" clearable />
        </el-form-item>
        <el-form-item label="创建时间">
            <el-date-picker v-model="requestData.createBegin" type="datetime" placeholder="开始时间" clearable />
            &nbsp;&nbsp;-&nbsp;&nbsp;
            <el-date-picker v-model="requestData.createEnd" type="datetime" placeholder="结束时间" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="listData">查询</el-button>
            <el-button type="info" @click="resetRequestData">重置</el-button>
        </el-form-item>
    </el-form>

    <el-dialog v-model="isOutBoundShow" title="出库" width="500" align-center>
        <el-form style="max-width: 600px" status-icon label-width="auto" class="demo-ruleForm" @submit.prevent>
            <el-form-item label="SN码">
                <el-input placeholder="在此扫描后自动出库" v-model="outBoundSN" autofocus @change="outBound">
                    <template slot="prepend">SN码输入框</template>
                </el-input>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="isAddShow" :title="addOrEditType == 0 ? '新增' : addOrEditType == 1 ? '编辑' : '复制'" width="500"
        align-center>
        <el-form style="max-width: 600px" :model="dataForm" status-icon label-width="auto" class="demo-ruleForm">
            <el-form-item label="序列号" prop="sn">
                <el-input placeholder="在此输入序列号自动匹配" v-model="dataForm.sn" autofocus @change="snMatch(dataForm.sn,true)">
                    <template slot="prepend">SN码输入框</template>
                </el-input>
            </el-form-item>
            <el-form-item label="设备名称" prop="name">
                <el-select filterable allow-create default-first-option :reserve-keyword="true" clearable v-model="dataForm.name" placeholder="请选择设备名称" size="large">
                    <el-option v-for="(item, index) in matchNameArr" :key="index" :label="item" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item label="型号" prop="model">
                <el-select filterable allow-create default-first-option :reserve-keyword="true" clearable
                    v-model="dataForm.model" placeholder="请选择设备型号" size="large">
                    <el-option v-for="(item, index) in matchModelArr" :key="index" :label="item" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item label="设备状态" prop="status">
                <el-select clearable v-model="dataForm.status" placeholder="请选择设备状态" size="large" style="width: 80px">
                    <el-option v-for="item in deviceStatus" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="dataForm.status == '其他'" label="备注" prop="remark">
                <el-input v-model="dataForm.remark" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitEditData">提交</el-button>
                <el-button @click="isAddShow = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-table :data="tableData.records" style="width: 100%;height: 462px;"
        :default-sort="{ prop: 'gmtCreate', order: 'descending' }" @sort-change="onSortChange"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="65" />
        <el-table-column prop="name" label="设备名称" sortable="custom" />
        <el-table-column prop="model" label="型号" sortable="custom" />
        <el-table-column prop="sn" label="序列号" sortable="custom" />
        <el-table-column prop="status" label="设备状态" sortable="custom" />
        <el-table-column prop="remark" label="备注" sortable="custom" />
        <el-table-column :formatter="formatOutboundStatus" label="出库状态" />
        <el-table-column prop="gmtCreate" sortable="custom" label="创建时间" />
        <el-table-column prop="gmtModified" sortable="custom" label="修改时间" />
        <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" @click="handleCopy(scope.row)">复制</el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination style="margin-top: 20px;margin-right: 20px;" v-model:current-page="requestData.page"
        v-model:page-size="requestData.pageSize" :page-sizes="[1, 10, 20, 50, 100]"
        layout="->,total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
</template>

<script setup>
import { ref, onMounted } from "vue";
import { list, addOrEditMaterial, deleteMaterial, outBoundMaterial, outBoundMaterialBatch, matchNameModelBySn } from "@/api/material";
import { ElMessage, ElMessageBox } from "element-plus";

const options = [
    {
        value: '0',
        label: '未出库',
    },
    {
        value: '1',
        label: '已出库'
    }
]
const deviceStatus = [
    {
        value: '正常',
        label: '正常',
    },
    {
        value: '异常',
        label: '异常'
    },
    {
        value: '其他',
        label: '其他'
    }
]
const tableData = ref({
    total: 0
})

const outBoundSN = ref('')

const dataForm = ref({
    id: '',
    name: '',
    model: '',
    sn: '',
    status: '',
    remark: '',
    gmtCreate: ''
})

const matchNameArr = ref([])

const matchModelArr = ref([])

const requestData = ref({
    pageSize: 10,
    page: 1,
    name: '',
    model: '',
    sn: '',
    status: '',
    remark: '',
    outBound: '',
    createBegin: '',
    createEnd: '',
    orderBy: 'gmtCreate',
    sort: 'DESC'
})

let selectionData = []
const isAddShow = ref(false)
const isOutBoundShow = ref(false)
const addOrEditType = ref(0)

onMounted(requestMethod)

function formatOutboundStatus(row, column, cellValue) {
    return row.outBound === 0 ? '未出库' : '已出库';
}

function handleSizeChange(val) {
    requestData.value.pageSize = val
    requestMethod()
}

function handleCurrentChange(val) {
    requestData.value.page = val
    requestMethod()
}

function handleSelectionChange(val) {
    selectionData = val
}

function resetRequestData() {
    requestData.value.name = ''
    requestData.value.model = ''
    requestData.value.sn = ''
    requestData.value.status = ''
    requestData.value.outBound = ''
    requestData.value.createBegin = ''
    requestData.value.createEnd = ''
    requestData.value.orderBy = 'gmtCreate'
    requestData.value.sort = 'DESC'
}

function onSortChange(sortData) {
    // 取消排序直接使用创建时间排倒叙
    if (!sortData.order) {
        requestData.value.orderBy = 'gmtCreate'
        requestData.value.sort = 'DESC'
        requestMethod()
        return
    }

    // 存在顺序再排序
    requestData.value.orderBy = sortData.prop
    if ('ascending' == sortData.order) {
        requestData.value.sort = 'ASC'
    } else {
        requestData.value.sort = 'DESC'
    }
    requestMethod()
}

function handleEdit(row) {
    dataForm.value.id = row.id
    dataForm.value.name = row.name
    dataForm.value.model = row.model
    dataForm.value.sn = row.sn
    dataForm.value.status = row.status
    dataForm.value.remark = row.remark
    dataForm.value.gmtCreate = row.gmtCreate
    snMatch(row.sn,false)
    addOrEditShow(1)
}

function handleCopy(row) {
    dataForm.value.id = ''
    dataForm.value.name = row.name
    dataForm.value.model = row.model
    dataForm.value.sn = row.sn
    dataForm.value.status = row.status
    dataForm.value.remark = row.remark
    dataForm.value.gmtCreate = row.gmtCreate
    snMatch(row.sn,false)
    addOrEditShow(2)
}

function snMatch(sn,isAdd) {
    matchNameModelBySn(sn).then(res => {
        matchNameArr.value = res.data.nameList
        matchModelArr.value = res.data.modelList
        // 查询有数据并且是新增，直接默认第一个
        if (matchNameArr.value.length > 0 && isAdd) {
            dataForm.value.name = matchNameArr.value[0]
        }
        if (matchModelArr.value.length > 0 && isAdd) {
            dataForm.value.model = matchModelArr.value[0]
        }
    })
}

function outBound() {
    if (outBoundSN.value === '') {
        console.log('没有SN不处理')
        return
    }

    outBoundMaterial(outBoundSN.value).then(res => {
        ElMessage({
            message: '出库成功',
            type: 'success',
        })

        requestMethod()
    })
}

function handleDelete(row) {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let arr = []
            arr.push(row.id)
            deleteMaterial(arr).then(res => {
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
                requestMethod()
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

function batchOutBound() {
    if (selectionData.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择需要出库的数据'
        })
        return
    }

    let checkFlag = selectionData.map(obj => obj.outBound).every(outBound => outBound === 0)
    if (!checkFlag) {
        ElMessage({
            type: 'warning',
            message: '包含已经出库的数据'
        })
        return
    }

    ElMessageBox.confirm(
        '确认批量出库吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let snArr = selectionData.map(obj => obj.sn)
            outBoundMaterialBatch(snArr).then(res => {
                ElMessage({
                    message: '批量出库成功',
                    type: 'success',
                })
                requestMethod()
            })
        })
        .catch(error => {

        })
}

function batchDelete() {
    if (selectionData.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择需要删除的数据'
        })
        return
    }

    ElMessageBox.confirm(
        '确认批量删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let arr = selectionData.map(obj => obj.id)
            deleteMaterial(arr).then(res => {
                ElMessage({
                    message: '批量删除成功',
                    type: 'success',
                })
                requestMethod()
            })
        })
        .catch(error => {

        })
}

function submitEditData() {
    if (dataForm.value.status === '' || dataForm.value.name === '' || dataForm.value.sn === '' || dataForm.value.model === '') {
        ElMessage({
            message: '请检查数据完整性',
            type: 'warning',
        })
        return
    }
    addOrEditMaterial(dataForm.value).then(res => {
        ElMessageBox.alert(addOrEditType.value == 0 ? '新增成功' : addOrEditType.value == 1 ? '编辑成功' : '复制成功', '提示', {
            confirmButtonText: '确认',
            callback: () => {
                requestMethod()
            }
        })
        isAddShow.value = false
    }).catch(err => {
        console.log(err)
    })
}

function addOrEditShow(addOrEditTypeInput) {
    isAddShow.value = true
    addOrEditType.value = addOrEditTypeInput
    if (addOrEditTypeInput === 0) {
        dataForm.value = {
            id: '',
            name: '',
            model: '',
            sn: '',
            status: '正常',
            remark: '',
        }
    }
}

function listData() {
    requestData.value.page = 1
    requestData.value.pageSize = 10
    requestMethod()
    ElMessage({
        message: '查询成功',
        type: 'success',
    })
}

async function requestMethod() {
    const data = await list(requestData.value);
    tableData.value = data.data
}
</script>